package com.lanhai.longheng.third;

import com.lanhai.longheng.beans.DeviceDataBean;
import com.lanhai.longheng.beans.DeviceMountBean;
import com.lanhai.longheng.enums.TransDirectionEnum;
import com.lanhai.longheng.enums.DeviceDataTypeEnum;
import com.lanhai.longheng.interfaces.IDeviceProtocol;
import com.lanhai.longheng.utils.Tools;

public class PSG implements IDeviceProtocol{

	@Override
	public byte[] applyTransfer(byte line, TransDirectionEnum type) {
		byte[] buf=new byte[8];
		buf[0]=line;
		switch(type) {
		case Both:
			buf[2]=1;
			buf[4]=1;
			break;
		case OnlyIn:
			buf[2]=1;
			buf[4]=0;
			break;
		case OnlyOut:
			buf[2]=0;
			buf[4]=1;
			break;  
		}
	
		return buf;
	}

	/*
	@Override
	public byte[] clear(byte line) { 
		//告之AGV已经离开，机台重置状态
		byte[] buf=new byte[8];
		buf[0]=1;
		buf[2]=2;
		buf[4]=2;
		
		return buf;
	}
	*/

	@Override
	public byte[] applyLeave(byte line, TransDirectionEnum type) {
		//PSG的罗工表示，机台满后主动给AGV发送允许 离开的信号 
		return new byte[1];
	}
 


	@Override
	public DeviceDataBean analyseData(String ip, byte[] buf) {
		DeviceDataBean obj=new DeviceDataBean();
		obj.setLine((byte)1);
		obj.setCmdStr(Tools.byte2HexStr(buf));
		 obj.setIp(ip);
		 
		 if(buf[2]!=buf[4]) {
			 //传输中的中间状态值，不用处理
			 return null;
		 }
		if(buf[1]==2) {
			//机台异常
			obj.setEventType(DeviceDataTypeEnum.Error);
			return obj;
		}
		if(buf[2]==3 ) {
			//允许离开
			obj.setEventType(DeviceDataTypeEnum.AllowLeave);
			return obj;
		}
		if(buf[2]==2 ) {
			//允许传输
			obj.setEventType(DeviceDataTypeEnum.AllowTrans);
			return obj;
		}
		DeviceMountBean mb=new DeviceMountBean(); 
		if(buf[2]==1||buf[2]==0) {
			//进料状态,
			obj.setEventType(DeviceDataTypeEnum.Info);
			int income=10-buf[6]-buf[7];
			if(income>10) income=10;
			if(income<0) income=0;
			 
			mb.setInNum(income); 
			if(income>=10) {
				mb.setAllowIn(true);
			} 
		}
		if(buf[4]==1||buf[4]==0) {
			//出料状态
			obj.setEventType(DeviceDataTypeEnum.Info);
			int outnum=buf[8]+buf[9];
			mb.setOutNum(outnum);
			if(outnum>=10) {
				mb.setAllowOut(true);
			} 
		}   
		obj.setBean(mb); 
		return obj;
	}
 
	@Override
	public byte[] agvLeave(byte line) {
		byte[] buf=new byte[8]; 
		buf[0]=line;
		return buf;
	}

	@Override
	public byte[] agvError(byte line) {
		byte[] buf=new byte[8]; 
		buf[0]=line;
		buf[2]=4;
		buf[4]=4;
		return buf;
	}

	@Override
	public byte[] applyRecieve(byte line, TransDirectionEnum type) {
		byte[] buf=new byte[8];
		buf[0]=line;
		switch(type) {
		case Both:
			buf[2]=5;
			buf[4]=5;
			break;
		case OnlyIn:
			buf[2]=5;
			buf[4]=0;
			break;
		case OnlyOut:
			buf[2]=0;
			buf[4]=5;
			break;  
		}
	
		return buf;
	}
 
}
